package com.zoro.barn.commons.webcommons.filters;

import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.http.MediaType;


import java.io.IOException;

/**
 * @author zhaoxingwu
 */
@Order(Integer.MIN_VALUE + 100)
public class MultipleReadableServletRequestFilter implements Filter {
    private final Logger logger = LoggerFactory.getLogger(getClass());

    MultipleReadableServletRequestFilter() {
    }

    @Override
    public void init(FilterConfig filterConfig)  {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        try {
            HttpServletRequest req = (HttpServletRequest) servletRequest;
            String contentType = req.getContentType();
            if (contentType != null && contentType.contains(MediaType.APPLICATION_JSON_VALUE)) {
                servletRequest = new MultipleReadableServletRequest((HttpServletRequest) servletRequest);
            }
        } catch (Exception e) {
            if (logger.isWarnEnabled()) {
                logger.warn("error occurred when create MultipleReadableServletRequest :" + e.getMessage());
            }
            servletRequest = new MultipleReadableServletRequest((HttpServletRequest) servletRequest, "{}");
        }
        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {

    }

}
